/*
 * ThreadVoltageMonitor.cpp
 *
 *  Created on: Jan 27, 2013
 *      Author: Drew Prevost
 */

#include "ThreadVoltageMonitor.h"

ThreadVoltageMonitor::ThreadVoltageMonitor(
                                            uint8_t nPin,
                                            int nPinMin,
                                            int nPinMax,
                                            int nVoltsMin,
                                            int nVoltsMax,
                                            unsigned long nReadFreqMicros )
{
  this->nPin = nPin;
  this->nPinMin = nPinMin;
  this->nPinMax = nPinMax;
  this->nVoltsMin = nVoltsMin;
  this->nVoltsMax = nVoltsMax;
  this->nReadFreqMicros = nReadFreqMicros;
  pinMode( nPin, INPUT );
}

ThreadVoltageMonitor::~ThreadVoltageMonitor()
{
  // TODO Auto-generated destructor stub
}

double ThreadVoltageMonitor::getVoltage()
{
  int nSensorVal = analogRead( nPin );
  return ( ( (double) ( nVoltsMax - nVoltsMin ) / (double) ( nPinMax - nPinMin ) ) * (double) nSensorVal );
}

void ThreadVoltageMonitor::reset()
{
  rollingAvg.reset();
}

void ThreadVoltageMonitor::setReadFreqMicros( unsigned long nReadFreqMicros )
{
  this->nReadFreqMicros = nReadFreqMicros;
}

unsigned long ThreadVoltageMonitor::getReadFreqMicros()
{
  return nReadFreqMicros;
}

bool ThreadVoltageMonitor::isVoltageTooLow()
{
  return ( rollingAvg.getAverage() <= nVoltsMin );
}

bool ThreadVoltageMonitor::isVoltageTooHigh()
{
  return ( rollingAvg.getAverage() >= nVoltsMax );
}

bool ThreadVoltageMonitor::run()
{
  threadMicroDelay.run();

  PT_BEGIN()
  ;

//  if( (nHybridMode == HYBRID_MODE_COAST) && (voltageMonitor.bCheckedThisCoast == false) )  // TODO: deal with this
//  {

  rollingAvg.add( getVoltage() );

  threadMicroDelay.setDelay( nReadFreqMicros );
  PT_SPAWN( threadMicroDelay );

//  }

PT_END()
;
return false;
}
